package redtankface.tasks;

import redtankface.EnemyInfo;
import redtankface.RedTankFace;
import redtankface.TankTask;
import redtankface.TankUtils;
import robocode.util.Utils;

/**
 * ScanTask
 *
 * @author: k.krestnikov
 * @date: 30.09.2010
 */
public class ScanTask extends TankTask {
    public static final double SCAN_OLD_MODIFIER = 3;
    public static final double DETECT_OLD_MODIFIER = 15;
    public static double mLastScan = 0;
    public static double SCAN_GROW = 10;

    public static double mScanStep = 10;

    public static EnemyInfo mLastScanned = null;
    private static final double RESCAN_PAUSE = 2;

    private static final double MIN_ROTATE_ANGLE = 0.3;

    private static boolean targeted = false;
    private static final double RETARGET_GAP = 10;

    public ScanTask(RedTankFace aRobot) {
        super(aRobot);
    }

    @Override
    public long getRating() {
        return (long) (50 + (mRobot.getTime() - mLastScan) * SCAN_OLD_MODIFIER +
                (mRobot.getTime() - mRobot.getLastDetect()) * DETECT_OLD_MODIFIER);
    }

    @Override
    public void p_doTask() {
        double angle = 0;
        if (!targeted && mLastScanned != null && (mRobot.getTime() - mLastScan) > RESCAN_PAUSE) {
            double absAngle = TankUtils.getAngle(mRobot.getCoord(), mLastScanned.getCoord(mRobot.getTime()));
            angle = Utils.normalRelativeAngle(absAngle - Math.toRadians(mRobot.getRadarHeading()));
            targeted = true;
        }
        if (angle >= MIN_ROTATE_ANGLE) {
            mRobot.turnRadarRight(angle + RETARGET_GAP);
        } else {
            mRobot.turnRadarRight(Math.min(Math.abs(mScanStep), 40) * Math.signum(mScanStep));
            if (mScanStep <= 39)
                mScanStep = -mScanStep;
            mScanStep += SCAN_GROW * Math.signum(mScanStep);
            mLastScan = mRobot.getTime();
        }
    }

    public static void dropScanSet() {
        mScanStep = 5;
    }

    public static void setLastScanned(EnemyInfo aLastScanned) {
        mLastScanned = aLastScanned;
    }

    public static void dropTargeted() {
        targeted = false;
    }
}
